package leetcode.editor.others;

import java.util.ArrayList;
import java.util.List;

public class 单词距离 {
    public static void main(String[] args) {
        String[] words = {"I","am","a","student","from","a","university","in","a","city"};
        String word1 = "a";
        String word2 = "student";

        System.out.println(findClosest(words, word1, word2));
    }

    public static int findClosest(String[] words, String word1, String word2) {
        int res = words.length;
        int index1 = -1;
        int index2 = -1;
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            if (word.equals(word1)) {
                index1 = i;
            } else if (word.equals(word2)) {
                index2 = i;
            }
            if (index1 >= 0 && index2 >= 0) {
                res = Math.min(res, Math.abs(index1 - index2));
            }
        }
        return res;
    }

    public static int findClosest1(String[] words, String word1, String word2) {
        List<Integer> wordList1 = new ArrayList<>();
        List<Integer> wordList2 = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                wordList1.add(i);
            }
            if (words[i].equals(word2)) {
                wordList2.add(i);
            }
        }
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < wordList1.size(); i++) {
            for (int j = 0; j < wordList2.size(); j++) {
                min = Math.min(min, Math.abs(wordList1.get(i) - wordList2.get(j)));
            }
        }
        return min;
    }
}
